<template>
  <div id="commentTextArea">
    <a-comment>
      <a-avatar
        slot="avatar"
        :src="userInfo.headUrl?userInfo.headUrl:'/assets/default-user.png'"
        :alt="userInfo.nickName"
      />
      <div slot="content">
        <a-form-item>
          <a-textarea :rows="4" v-model="content" :placeholder="commentReplyBody.placeholder"></a-textarea>
        </a-form-item>
        <a-form-item>
          <a-button v-if="isUserLogin" htmlType="submit" :loading="submitting" @click="handleSubmit" type="primary"
                    :disabled="content===''">
            提交评论
          </a-button>
          <a-button v-else htmlType="submit" @click="showLoginDialog" type="primary">
            登录评论
          </a-button>
        </a-form-item>
      </div>
    </a-comment>

    <!--留言区-->
    <a-list
      v-if="pagination.total>0"
      :dataSource="comment.records"
      :pagination="pagination"
      :header="`${pagination.total}个评论`"
      itemLayout="horizontal"
    >
      <a-list-item slot="renderItem" slot-scope="item, index">
        <a-comment
          :author="item.activeNickName"
          :avatar="item.activeUserHeadUrl"
        >
          <template slot="content">
            <div :class="item.justComment?`justComment`:``">{{item.content}}</div>
          </template>
          <!--评论回复操作-->
          <template slot="datetime">
            <span class="comment-tooltip">{{item.createTime}}</span>
            <span class="comment-tooltip" @click="commentReplyStarClick(item)"><a-icon type="like"/><span>{{item.starCount}}</span></span>
            <span :id="`comment-`+item.id" class="comment-tooltip" @click="commentReplyClick(item,`B_COMMENT_REPLY`)"><a-icon
              type="message"/>回复</span>
            <span class="comment-tooltip" v-if="item.commentReplies && item.commentReplies.length>0"
                  @click="commentCollapseClick(item)">
              <span>回复共（{{item.replyCount}}）条</span>
              <a-icon :type="item.expand?`caret-down`:`caret-up`"/></span>
          </template>

          <!--子回复1-->
          <a-comment v-if="item.expand" v-for="reply in item.commentReplies">
            <template slot="actions">
              <span @click="commentReplyStarClick(reply)">
                  <a-icon type="like" theme="outlined"/><span>{{reply.starCount}}</span>
              </span>
              <span @click="commentReplyClick(reply,`B_REPLY_REPLY`)">
                 <a-icon type="message"/><span>回复</span>
              </span>
            </template>
            <a slot="author">{{reply.activeNickName}} <b>回复</b> {{reply.passiveNickName}}</a>
            <a-avatar
              slot="avatar"
              :src="reply.activeUserHeadUrl"
              :alt="reply.activeNickName"
            />
            <template slot="content">
              <div :class="reply.justComment?`justComment`:``">{{reply.content}}</div>
            </template>
          </a-comment>
          <div style="text-align: center">
            <a-spin v-if="item.loadingMoreClick"/>
            <a-button v-if="item.commentReplies && item.commentReplies.length<item.replyCount&&item.expand"
                      @click="onLoadMore(item)"
                      type="link">
              加载更多
            </a-button>
          </div>

        </a-comment>
      </a-list-item>
    </a-list>


  </div>
</template>
<script>
  import { mapGetters, mapActions } from 'vuex'
  import { blogCommentReplyQuery, makeBlogComment, makeCommentReply, makeCommentReplyAgree } from '@/api/blog'
  import moment from 'moment'
  import _ from 'lodash'

  export default {
    data() {
      return {
        submitting: false,  //提交按钮加载状态
        content: '',
        moment
      }
    },
    computed: {
      ...mapGetters(['blog', 'comment', 'pagination', 'token', 'userInfo', 'commentReplyBody']),
      isUserLogin() {
        return !_.isEmpty(this.token)
      }
    },
    created() {
      const blogId = this.blog.id
      let placeholder = `亲爱的${this.userInfo.userName ? this.userInfo.userName : '上帝（靓仔/美女）'}，快来发表你的评论包(*^__^*)……`
      this.$store.dispatch('setCommentReplyBody', { type: 'B_BLOG_COMMENT', obj: this.blog, placeholder })
      this.$store.dispatch('blogCommentReplyQuery', { blogId, type: 'B_BLOG_COMMENT', currentPage: 1 })
    },
    methods: {
      ...mapActions(['setCommentDatasource']),
      /**
       * 博客评论回复点击
       */
      commentCollapseClick(comment) {
        comment.expand = !comment.expand
      },
      /**
       * 评论回复点评操作
       */
      commentReplyStarClick(commentReply) {
        makeCommentReplyAgree(commentReply.id).then((res) => {
          if (res.code === '200') {
            commentReply.starCount++
            this.$message.success('评论点赞成功。')
          } else {
            this.$message.warning(res.msg)
          }
        }).catch((err) => {
          this.$message.error('评论失败.', err)
        })
      },
      /**
       * 对评论或者回复进行发表言论
       */
      commentReplyClick(commentReply, type) {
        let placeholder = `回复：${commentReply.activeNickName}`
        this.$store.dispatch('setCommentReplyBody', { type, obj: commentReply, placeholder })
        document.getElementById('commentTextArea').scrollIntoView(true, {
          behavior: 'smooth',
          block: 'start',
          inline: 'nearest'
        })
      },
      /**
       * 暂时登陆界面
       */
      showLoginDialog() {
        this.$store.dispatch('setLoginVisible', true)
        this.$store.dispatch('setLoginModeType', 'blog')
      },
      /**
       * 加载更多评论
       */
      onLoadMore(comment) {
        comment.loadingMore = true
        comment.loadPageNo++
        blogCommentReplyQuery(comment.id, 'B_COMMENT_REPLY', comment.loadPageNo, 3).then((res) => {
          comment.loadingMore = false
          if (res.code === '200') {
            // 附带一些界面交互属性
            _.forEach(res.data.records, function(item) {
              comment.commentReplies.push(item)
            })
          } else {
            this.$message.warning(res.msg)
          }
        }).catch((err) => {
          this.$message.error('评论失败.', err)
        })
      },

      /**
       * 评论和回复http请求
       * @param requestBody
       */
      makeCommentReplyRequest(requestBody) {
        makeCommentReply(requestBody).then((res) => {
          this.submitting = false
          if (res.code === '200') {
            // 查找当前回复所在的评论对象，并给评论对象的最顶层添加回复信息
            let copyComments = _.cloneDeep(this.comment)
            let comment = _.filter(copyComments.records, { id: requestBody.parentId })
            if (comment && comment.length === 1) {
              var commentInfo = comment[0]
              commentInfo.replyCount++
              if (!commentInfo.commentReplies) {
                commentInfo.commentReplies = []
              }
              if (commentInfo.commentReplies && commentInfo.commentReplies.length > 2) {
                commentInfo.commentReplies.pop()
              }
              var data = res.data
              data.justComment = true
              commentInfo.commentReplies.unshift(data)
            }
            this.setCommentDatasource(copyComments)
            this.$message.success('博客评论成功。')
          } else {
            this.$message.warning(res.msg)
          }
          this.content = ''
          document.getElementById(`comment-${requestBody.parentId}`).scrollIntoView(true, {
            behavior: 'smooth',
            block: 'start',
            inline: 'nearest'
          })
        }).catch((err) => {
          this.$message.error('评论失败.')
          this.submitting = false
        })
      },
      /**
       * 总记录数+1操作
       * @param total 总记录数字
       */
      totalPlusOne() {
        const total = this.pagination.total + 1
        let pagination = { total, pageSize: 5 }
        this.$store.dispatch('setBlogPagination', pagination)
      },
      /**
       * 给评论附加默认属性
       * @param comment
       */
      attacheDefaultAtt(comment) {
        comment.loadingMore = false
        comment.expand = true
        comment.loadPageNo = 1
        // justComment有一个灰色的底色进行高亮显示
        comment.justComment = true
      },
      handleSubmit() {
        this.submitting = true
        const content = this.content
        const blogId = this.blog.id
        let vm = this
        if (this.commentReplyBody.type === 'B_BLOG_COMMENT') {
          const passiveUserId = this.blog.userId
          const parentId = blogId
          let requestBody = { passiveUserId, parentId, content }
          makeBlogComment(requestBody).then((res) => {
            vm.submitting = false
            if (res.code === '200') {
              this.totalPlusOne()
              let copyComments = _.cloneDeep(vm.comment)
              if (copyComments.records && copyComments.records.length > 4) {
                copyComments.records.pop()
              }
              var data = res.data
              this.attacheDefaultAtt(data)
              copyComments.records.unshift(data)
              vm.setCommentDatasource(copyComments)
              vm.$message.success('博客评论成功。')
            } else {
              vm.$message.warning(res.msg)
            }
            vm.content = ''
          }).catch((err) => {
            this.$message.error('评论失败.')
            vm.submitting = false
          })
        } else if (this.commentReplyBody.type === 'B_COMMENT_REPLY') {
          const passiveUserId = this.commentReplyBody.obj.activeUserId
          const parentId = this.commentReplyBody.obj.id
          this.makeCommentReplyRequest({ blogId, passiveUserId, parentId, content })
        } else if (this.commentReplyBody.type === 'B_REPLY_REPLY') {
          const passiveUserId = this.commentReplyBody.obj.activeUserId
          const parentId = this.commentReplyBody.obj.parentId
          this.makeCommentReplyRequest({ blogId, passiveUserId, parentId, content })
        }
      },
      handleChange(e) {
        // this.value = e.target.value
      }
    }
  }
</script>

<style scoped>
  .comment-tooltip {
    margin-left: 10px;
    cursor: pointer;
  }

  .comment-tooltip:hover {
    font-weight: bold;
  }

  .justComment {
    font-weight: bold;
    font-family: Verdana, Geneva, sans-serif;
    size: 14px;
    color: black;
    opacity: 1;
    moz-opacity: 1;
  }
</style>